package cn.cutie.clot.fs;

import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.UUID;

/**
 * @Description:
 * @Author: Cutie
 * @CreateDate: 2024/7/16 15:18
 * @Version: 0.0.1
 */
public class FileUtils {

    static String DEFAULT_MIME_TYPE = "application/octet-stream";
    public static String getMimeType(String fileName) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String content = fileNameMap.getContentTypeFor(fileName);
        return content == null ? DEFAULT_MIME_TYPE : content;
    }

    public static void init(String uploadPath){
        File dir = new File(uploadPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        for (int i = 0; i < 256; i++) {
            String subDir = String.format("%02x", i);
            File file = new File(uploadPath + "/" + subDir);
            if (!file.exists()){
                file.mkdirs();
            }
        }
    }

    public static String getUUIDFile(String filename) {
        return UUID.randomUUID().toString() + getExt(filename);
    }

    public static String getSubDir(String filename) {
        return filename.substring(0, 2);
    }

    private static String getExt(String originalFilename) {
        return originalFilename.substring(originalFilename.lastIndexOf("."));
    }

    public static void main(String[] args) {
        System.out.println(getMimeType("test.txt"));
    }

    @SneakyThrows
    public static void writeMeta(File metaFile, FileMeta fileMeta) {
        String jsonString = JSON.toJSONString(fileMeta);
        Files.writeString(Paths.get(metaFile.getAbsolutePath()), jsonString, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
    }

    @SneakyThrows
    public static void writeString(File metaFile, String jsonString) {
        Files.writeString(Paths.get(metaFile.getAbsolutePath()), jsonString, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
    }

    @SneakyThrows
    public static void download(String downloadUrl, File file) {
        System.out.println("===> download file downloadUrl:" + downloadUrl + " absolutePath:" + file.getAbsolutePath());
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<?> entity = new HttpEntity<>(new HttpHeaders());
        ResponseEntity<Resource> exchange = restTemplate
                .exchange(downloadUrl, HttpMethod.GET, entity, Resource.class);

        InputStream is = new BufferedInputStream(exchange.getBody().getInputStream());
        byte[] buffer = new byte[16*1024];
        OutputStream os = new FileOutputStream(file);
        while (is.read(buffer) != -1) {
            os.write(buffer);
        }
        os.flush();
        os.close();
        is.close();
    }
}
